package com.fz.security.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fz.common.ResultCode;
import com.fz.dto.client.login.WxAuthDto;
import com.fz.entity.member.Member;
import com.fz.mapper.member.MemberMapper;
import com.fz.security.AuthExceptionDto;
import com.fz.security.tokens.WeChatAuthenticationToken;
import com.fz.utils.JacksonUtils;
import com.fz.utils.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
@Component
public class WeChatAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private InitUserProvider initUserProvider;

    /**
     * @方法描述: 微信授权登录
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/2/26
     */
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取传输过来的json字符串
        String jsonStr = (String) authentication.getPrincipal();
        WxAuthDto wxAuthDto = JacksonUtils.string2Obj(jsonStr,WxAuthDto.class);
        //验证unionid是否传输
        if (StringUtils.isEmpty(wxAuthDto.getUnionId())) {
            throw new BadCredentialsException(JacksonUtils.obj2String(new AuthExceptionDto(ResultCode.NO_UNION_ID_ERROR.getResultCode(), ResultCode.NO_UNION_ID_ERROR.getMessage())));
        }
        //根据unionid查询用户
        LambdaQueryWrapper<Member> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Member::getUnionId,wxAuthDto.getUnionId());
        Member member = memberMapper.selectOne(lambdaQueryWrapper);
        if (null == member) {
            //如果未查询到该用户，则对该用户进行注册
            member = initUserProvider.initMember(wxAuthDto,wxAuthDto.getAuthType());
        }
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(member.getUnionId(), wxAuthDto.getOpenId(), listUserGrantedAuthorities(member.getUid()));
        result.setDetails(member);
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (WeChatAuthenticationToken.class.isAssignableFrom(authentication));
    }

    private Set<GrantedAuthority> listUserGrantedAuthorities(Integer uid) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        return authorities;
    }
}
